<?php
/**
 * Created by PhpStorm.
 * User: caoyixian
 * Date: 2017/6/27 0027
 * Time: 下午 4:07
 */


class UploadFile{

    protected $config;
    public function __construct($config=array())
    {
        if(is_array($config) && count($config)>=2) {
            $this->config = $config;
        }else{
            $this->config = self::default_config();
        }
    }

    public function execute($field_name){

        $files = $_FILES;
        if(is_array($files) && count($files)>=1){
            $file = (object)$files[$field_name];
            $origin_filename = $file->name;
            $type = $file->type;
            $temp_filepath = $file->tmp_name;
            $file_size = $file->size;
            $error = $file->error;
            $save_filepath = $this->config['upload_path'];
            $sub_filepath = $this->config['sub_path'];
            $save_filepath = trim($save_filepath,"/")."/".trim($sub_filepath,"/");
            //创建目录
            if(!is_dir($save_filepath)){
                mkdir($save_filepath,0777,true);
            }
            //验证文件大小
            if(intval($this->config['max_size'])<($file_size/1000)){
                return array('code'=>1,'msg'=>'文件大小超出限制');
            }

            //保存文件名
            $save_filename = $this->config['file_name'].".".self::getfile_ext($type);
            //文件在服务器上的完整路径
            $full_file = $save_filepath."/".$save_filename;
            //验证文件类型
            $ext_arr = explode("|",$this->config['allowed_types']);
            if(!in_array(self::getfile_ext($type),$ext_arr)){
                return array('code'=>1,'msg'=>'文件类型不合格,当前为'.self::getfile_ext($type));
            }
            if($error===0){
                move_uploaded_file($temp_filepath, $full_file);
                return array('code'=>0,'data'=>array('origin_name'=>$origin_filename,'type'=>$type,'save_name'=>$save_filename,'sub_path'=>$sub_filepath,'save_path'=>$save_filepath,'full_file_path'=>$full_file,'size'=>$file_size));
            }

            return array('code'=>1,'msg'=>'未知错误请检查服务器配置');

        }else{

            return array('code'=>1,'msg'=>'文件上传失败');

        }


    }





    protected static function getfile_ext($type){

      if(stripos($type,"/")){
          $ext = explode("/",$type);
          return $ext[1];
      }else{
          return $type;
      }

    }


    protected static function default_config(){
        $config['upload_path']      = $_SERVER['DOCUMENT_ROOT'].'/Public/Uploads';
        $config['sub_path'] = date("Y-m-d");
        $config['allowed_types']    = 'gif|jpg|png|jpeg';
        $config['max_size']     = 100;
        $config['max_width']        = 1024;
        $config['max_height']       = 768;
        $config['file_name'] = md5(uniqid());
        return $config;
    }



}